package com.zy.rushjdcloud.rush;

import com.zy.rushjdcloud.RushRequestParams;
import com.zy.rushjdcloud.service.ScheduledService;
import com.zy.rushjdcloud.task.RushTask;
import com.zy.rushjdcloud.task.ScheduledTask;
import com.zy.rushjdcloud.task.TaskParams;
import com.zy.rushjdcloud.util.ThreadPoolService;
import com.zy.rushjdcloud.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * rush
 *
 * @author zy
 * @date 2019-10-3 21:40
 */
@Controller
@RequestMapping("/rush")
public class RushJDCloudController {

    @Autowired
    private ScheduledService scheduledService;
    @Autowired
    private ThreadPoolService threadPoolService;

    private static final Map<String, List<String>> msg = new HashMap<>();

    private static final String DEFAULT_RUSH_DATE;
    private static final String DEFAULT_PARAM;
    private static final String DEFAULT_COOKIE;
    private static final Long DEFAULT_INTERVAL;
    private static final String DEFAULT_TARGET_URL;
    private static final String DEFAULT_REFERER;

    /**
     * init default
     */
    static{
        LocalDateTime now = LocalDateTime.now();
        DEFAULT_RUSH_DATE = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
        DEFAULT_PARAM = "{\"activityCode\":\"ada8afd783dd4772b8b9e356b8e018e0\",\"activityProductCode\":\"8ddc3c47f4404732aaebe20127f6aeeb\",\"dataCenter\":\"cn-east-2\",\"count\":1,\"chargeMode\":\"3\",\"chargeDuration\":\"1\",\"chargeUnit\":\"4\",\"serviceCode\":\"vm|ip\",\"activityPriceCode\":\"b0a41f1e463d4f7b99c92cda0873101f\",\"imageId\":\"img-kxs3xhhwy6\",\"instanceType\":\"h.g2.large\",\"lAz\":\"cn-east-2a\",\"bootVolumeType\":\"hdd.std1\",\"vpcId\":\"vpc-74kckopxzv\",\"subnetId\":\"subnet-zr0kial21r\",\"floatingIP\":{\"rate\":1,\"provider\":\"BGP\"}}";
        DEFAULT_COOKIE = "_ga=GA1.2.2048379531.1570067776; _gid=GA1.2.1257476233.1570067776; 3AB9D23F7A4B3C9B=XXYYKU6NSMCI7JFBR6DBV5BSIO3NDDGOWXONHABDWGCMEMOSJEBBXOBYM5GZ7SQ6XTQX63SRE7ISPK2DLG5VF7IKEQ; jdcloud_sitelang=cn; jdcloud_sitelang_server=cn; __jdv=269124599|DMT_baidubrand|2019baidubrand|title|NA|1570154141839; Hm_lvt_38f625421267eb5065e400d79fc42c74=1570097849,1570118461,1570118541,1570154142; vcn=D0E927B847CFC96BAF4D59D37782C7604110BF2E7DD1F8B1C2CA61CBB2290CF43ABC0A5B5D9C7941BF49D2E4B516EA1415D426397539BE11804A3DB5903E9D0CA6938855510FF8678C1BE34DA196D767; _gat=1; thor=949AE864260345ADFBA950EAFF1EA7DE00BE768E1457E7C1C0866180696D9A234452029B17ADC19009DEB7B02B1F4BD6984AAF12AA953A177CB7EE78B4904230EC10221B5951C3FB3068B52735E18C28803B0D63AB37786BECF4B5AF44A0D134B776BF46827A0D7C54B61F541E8C1F9757D18F5203EDA7B880CB4F83B987256368AAF412E2801848BFBE1BA320C7173F; pin=15228163685_p; unick=%E8%96%9B%E5%AE%9A%E8%B0%94%E7%9A%84%E7%8C%ABsssss; __jda=269124599.15700335516621480019288.1570033552.1570118460.1570154142.6; __jdc=269124599; Hm_lpvt_38f625421267eb5065e400d79fc42c74=1570154187; __jdb=269124599.5.15700335516621480019288|6.1570154142";
        //默认一小时间隔请求一次
        DEFAULT_INTERVAL = 60 * 60 * 1000L;
        DEFAULT_TARGET_URL = "https://promotion.jdcloud.com/u/activity/createPackageResource";
        DEFAULT_REFERER = "https://promotion.jdcloud.com/productTrialforPay";
    }

    @RequestMapping("/data")
    @ResponseBody
    public Map<String, Object> rush(RushRequestParams requestParams) {

        if (StringUtils.isEmpty(requestParams.getRushDate())) {
            requestParams.setRushDate(DEFAULT_RUSH_DATE);
        }
        if (StringUtils.isEmpty(requestParams.getParam())) {
            requestParams.setParam(DEFAULT_PARAM);
        }

        if (StringUtils.isEmpty(requestParams.getCookie())) {
            requestParams.setCookie(DEFAULT_COOKIE);
        }
        if (StringUtils.isEmpty(requestParams.getTargetUrl())) {
            requestParams.setTargetUrl(DEFAULT_TARGET_URL);
        }
        if (StringUtils.isEmpty(requestParams.getReferer())) {
            requestParams.setReferer(DEFAULT_REFERER + "?uuid=" + UUIDUtil.get());
        }

        if (null == requestParams.getInterval()) {
            requestParams.setInterval(DEFAULT_INTERVAL);
        }


        TaskParams taskParams = new TaskParams(msg);

        //result
        Map<String, Object> result = new HashMap<>();
        try {
            RushTask rushTask = new RushTask(threadPoolService.getPool(), requestParams);

            ScheduledTask scheduledTask = new ScheduledTask("rushTask", "doRush", taskParams,
                    getTimeMillis(requestParams.getRushDate()), requestParams.getInterval(), rushTask);
            if (scheduledService.exists(scheduledTask)) {
                scheduledService.updateTask(scheduledTask);
            } else {
                scheduledService.addTask(scheduledTask);
            }
            result.put("code", "0");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "-1");
        }

        return result;
    }


    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/add-data")
    public String addData() {
        return "add-data";
    }


    @RequestMapping("/view-msg")
    @ResponseBody
    public Map<String, List<String>> msg() {
        return msg;
    }


    /**
     * 获取指定时间对应的毫秒数
     *
     * @return
     */
    private long getTimeMillis(String rushDate) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss:SSS");
            Date date = dateFormat.parse(rushDate);
            return date.getTime() - System.currentTimeMillis();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
